/*
 * InvulgoTracker
 * Copyright (C) Thomas Andersen 2011 <thomas.1.andersen@gmail.com>
 *
 * InvulgoTracker is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * InvulgoTracker is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <config.h>

#include "gettextmacro.h"
#include "workbalance.h"
#include "day.h"
#include "prefs.h"

WorkBalance::WorkBalance(int year, int month, int day)
{
    this->year = year;
    this->month = month;
    this->day = day;
    this->prevTime = NULL;
}

WorkBalance::~WorkBalance()
{
}

int WorkBalance::GetDayBalance()
{
    return 0;
}

int WorkBalance::GetMonthToDateBalance()
{
    Day dayfinder(year, month, -1);
    Prefs prefs;
    double totalWorkhours = 0;
    double totalActual = 0;

    // Calc needed workhours.
    for(int d=1;d<=day;++d) {
        TaskTime tt(year, month + 1, d);
        totalWorkhours += prefs.GetWorkhours(tt.GetWeekDay()) / 60;
    }

    // Calc actual workhours.
    totalTime.TimeFromString((char*)"00:00");
    dayfinder.FindFiles();
    int y,m,d;
    while(dayfinder.FindNext(y,m,d)) {
        if (d<=day) {
            Day dayloader(y,m,d);
            dayloader.Load(this);

            if (prevTime) {
                delete prevTime;
                prevTime = NULL;
            }
        }
    }
    totalActual = totalTime.Minutes() / 60;
    totalActual -= totalWorkhours;
    return (int)(totalActual);
}

void WorkBalance::Data(gchar *name, gchar *timeStr, TaskId id)
{
    TaskTime taskTime;
    taskTime.TimeFromString(timeStr);
    free(timeStr);
    free(name);
    if (prevTime) {
        TaskTime diff = taskTime.SubTime(*prevTime);
        totalTime = totalTime.AddTime(diff);
        delete prevTime;
        prevTime = NULL;
    }
    prevTime = new TaskTime(taskTime);
}
